#define _CRT_SECURE_NO_WARNINGS
#include "List.h"

ListNode* ListCreate() {
	ListNode* head = (ListNode*)malloc(sizeof(ListNode));
	if (head != NULL) {
		head->next = head;
		head->prev = head;
		return head;
	}
	return NULL;
}
ListNode* BuyListNode(LTDataType x) {
	ListNode* head = (ListNode*)malloc(sizeof(ListNode));
	if (head != NULL) {
		head->data = x;
		head->next = NULL;
		head->prev = NULL;
		return head;
	}
	return NULL;
}
ListNode* ListInit() {
	ListNode* head = BuyListNode(-1);
	if (head!=NULL) {
		head->next = head;
		head->prev = head;
		return head;
	}
	return NULL;
}
void ListPushBack(ListNode* phead, LTDataType x) {
	assert(phead);
	/*ListNode* newnode = BuyListNode(x);
	ListNode* cur = phead->prev;
	cur->next = newnode;
	newnode->prev = cur;
	newnode->next = phead;
	phead->prev = newnode;*/
	ListInsert(phead,x);
}
void ListPrint(ListNode* phead) {
	ListNode* cur = phead->next;
	while (cur != phead) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
void ListPopBack(ListNode* phead) {
	assert(phead);
	if (phead != phead->next) {
		/*ListNode* cur = phead->prev;
		phead->prev = cur->prev;
		cur->prev->next = phead;
		free(cur);*/
		ListErase(phead->prev);
	}
	else {
		return;
	}
	
}
void ListPushFront(ListNode* phead, LTDataType x){
	/*ListNode* cur = phead->next;
	ListNode* newnode = BuyListNode(x);
	newnode->next = cur;
	cur->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;*/
	ListInsert(phead->next, x);
}
void ListPopFront(ListNode* phead) {
	assert(phead);
	if (phead != phead->next) {
		/*ListNode* cur = phead->next;
		phead->next = cur->next;
		cur->next->prev = phead;
		free(cur);*/
		ListErase(phead->next);
	}
	else {
		return;
	}
}
ListNode* ListFind(ListNode* phead, LTDataType x) {
	assert(phead);
	ListNode* pos = phead->next;
	while (pos != phead) {
		if (pos->data == x) {
			return pos;
		}
		pos = pos->next;
	}
	return NULL;
}
void ListDestory(ListNode* phead) {
	assert(phead);
	ListNode* tail = phead->next;
	while (tail != phead) {
		ListNode* next = tail->next;
		free(tail);
		tail = next;
	}
	free(phead);
}
void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuyListNode(x);
	ListNode* prev = pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}
void ListErase(ListNode* pos) {
	assert(pos);
	ListNode* next = pos->next;
	ListNode* prev = pos->prev;
	prev->next = next;
	next->prev = prev;
	free(pos);
}